package com.example.demo.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.demo.model.SysUser;
import org.springframework.stereotype.Service;


@Service("TokenService")
public class TokenService {
    public String getToken(SysUser sysUser) {
        return JWT.create().withAudience(String.valueOf(sysUser.getUserId()), sysUser.getLoginName())// 将 user id 保存到 token 里面
                .sign(Algorithm.HMAC256(sysUser.getLoginPwd()));
    }

    public Integer getUserId(String token){
        return Integer.valueOf(JWT.decode(token).getAudience().get(0));
    }

    public String getUserName(String token){
        return JWT.decode(token).getAudience().get(1);
    }

    public void verify(SysUser user, String token) {
        JWT.require(Algorithm.HMAC256(user.getLoginPwd())).build().verify(token);
    }
}
